using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using BuildingBlocks.Abstractions.Permissions;
using Identity.Application.Contracts.Services;
using Identity.Application.PermissionKeyResourceIds.Interfaces;
using Identity.Application.PermissionKeyResourceIds.Queries;
using MediatR;

namespace Identity.Application.PermissionKeyResourceIds.QueryHandlers
{
    public class GetPermissionKeyResourceIdByPermissionKeyQueryHandler : IRequestHandler<GetPermissionKeyResourceIdByPermissionKeyQuery, PermissionBindingDto>
    {
        private readonly IApiPermissionBindingReadService _permissionKeyResourceIdReadService;
        public GetPermissionKeyResourceIdByPermissionKeyQueryHandler(IApiPermissionBindingReadService permissionKeyResourceIdReadService)
        {
             _permissionKeyResourceIdReadService= permissionKeyResourceIdReadService;
        }
        public async Task<PermissionBindingDto> Handle(GetPermissionKeyResourceIdByPermissionKeyQuery request, CancellationToken cancellationToken)
        {
            var permissionBinding = await _permissionKeyResourceIdReadService.GetBindingsByPermissionKeyAsync(request.permissionKey, cancellationToken);
            if (permissionBinding == null || !permissionBinding.Any())
            {
                return null;
            }
            return permissionBinding.FirstOrDefault();
        }
    }
}